package com.coinworld.utils;

import org.springframework.beans.BeanUtils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;


public class CollectionEachCopy {

    private CollectionEachCopy(){}

    public static <S, T> List<T> generatorList(List<S> sourceList, Class<T> targetElemClass) {
        if (sourceList == null) {
            return null;
        } else {
            List<T> target = new ArrayList<>();

            for (S s : sourceList) {
                T t = generatorObject(s, targetElemClass);
                target.add(t);
            }

            return target;
        }
    }

    public static <S, T> T[] generatorArray(S[] sourceArray, Class<T> targetElemClass) {

        T[] targetArray = (T[])Array.newInstance(targetElemClass, sourceArray.length);

        for(int i = 0; i < sourceArray.length; ++i) {
            T t = generatorObject(sourceArray[i], targetElemClass);
            targetArray[i] = t;
        }

        return targetArray;
    }

    public static <T> T generatorObject(Object source, Class<T> targetClass) {
        if (source == null) {
            return null;
        } else {
            try {
                T t = targetClass.newInstance();
                BeanUtils.copyProperties(source, t);
                return t;
            }catch (Exception e){
                throw new RuntimeException("", e);
            }
        }
    }
}
